package com.eh.act;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dbdao.LoginUpBeanDao;
import com.eh.adapter.BaseRecyclerAdp;
import com.eh.adapter.TestAdapter;
import com.eh.bean.BaseBean;
import com.eh.bean.SearchResultItem;
import com.eh.bean.SearchResultItemBean;
import com.eh.db.dao.DbFactory;
import com.eh.db.global.SqlColum;
import com.eh.db.orm.dao.DbModel;
import com.eh.library.R;
import com.eh.logutil.LogUtil;
import com.eh.mitakebus.MitakeBus;
import com.eh.uploadbean.LoginBean;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by zhangxiaowei on 16/11/10.
 */

public class MainAct extends Activity {
    private final String TAG = MainAct.class.getSimpleName();
    private Map<String, String> parms;
    StringRequest request;
    LoginUpBeanDao dao;
    TestAdapter mallAdapter;
    String[] subtype =
            {
                    "sh", "sz", "hk"
            };
    EditText search;
    List<SearchResultItem> beanList = new ArrayList<>();
    List<SearchResultItemBean> beans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        JSON.parseObject()
        LogUtil.i(TAG, "MainAct:onCreate: [22222]=");
        MitakeBus.getDefaut().register(this);
        LogUtil.i(TAG, "MainAct:onCreate: [1111]=");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MemoryPersistence persistence = new MemoryPersistence();
                    MqttClient mqttClient = new MqttClient("tcp://114.80.155.61:22017 ", "mToken", persistence);
                    mqttClient.setCallback(new MqttCallback() {
                        @Override
                        public void connectionLost(Throwable cause) {

                        }

                        @Override
                        public void messageArrived(String topic, MqttMessage message) throws Exception {

                        }

                        @Override
                        public void deliveryComplete(IMqttDeliveryToken token) {

                        }
                    });
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }).start();


//        init();

    }

    private void init() {
        TextView textView = (TextView) findViewById(R.id.content);
        search = (EditText) findViewById(R.id.et_search);
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence str, int start, int before, int count) {
                if (!TextUtils.isEmpty(str)) {
                    DbModel<SearchResultItem> model = DbFactory.getInstance().openSession(SearchResultItem.class);
                    SqlColum sql = new SqlColum();
                    sql.selectAll().fromTable().whereColumLike("stockID", str.toString());
                    beanList = model.queryRaw(sql, null);
                    mallAdapter.notifyData(beanList);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(MainAct.this, SecondAct.class);
//                startActivity(intent);
//                addnum();
//                mallAdapter.notifyData(beanList);

                for (int i = 0; i < 30; i++) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DbModel model = DbFactory.getInstance().openSession(SearchResultItem.class);
                            LogUtil.i(TAG, "MainAct:onClick: [vvvvvvvv]=" + beanList.size() + "  " + beanList);
                            model.insertList(beanList);
                        }
                    }).start();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DbModel<SearchResultItem> model = DbFactory.getInstance().openSession(SearchResultItem.class);
                            LogUtil.i(TAG, "MainAct:onClick: [vvvvvvvv]=" + beanList.size() + "  " + beanList);
                            for (SearchResultItem bean : beanList)
                                model.insert(bean);
                        }
                    }).start();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DbModel<SearchResultItemBean> model = DbFactory.getInstance().openSession(SearchResultItemBean.class);
                            LogUtil.i(TAG, "MainAct:onClick: [vvvvvvvv]=" + beanList.size() + "  " + beanList);
                            model.insertList(beans);
                        }
                    }).start();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DbModel<SearchResultItemBean> model = DbFactory.getInstance().openSession(SearchResultItemBean.class);
                            LogUtil.i(TAG, "MainAct:onClick: [vvvvvvvv]=" + beanList.size() + "  " + beanList);
                            for (SearchResultItemBean bean : beans)
                                model.insert(bean);
                        }
                    }).start();
                }


            }
        });

        beans = addnumBean();
        addnum();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DbModel model1 = DbFactory.getInstance().openSession(SearchResultItemBean.class);

                DbModel<SearchResultItem> model = DbFactory.getInstance().openSession(SearchResultItem.class);
                LogUtil.i(TAG, "MainAct:onCreate: [cccccccc]= " + model.queryCount() + "  " + model1.queryCount());
                model.insertList(beanList);
                List<SearchResultItem> beanList1 = model.queryList();
                LogUtil.i(TAG, "MainAct:run: []=" + beanList1);
            }
        }).start();
        mallAdapter = new TestAdapter(MainAct.this, beanList);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mallAdapter);

        mallAdapter.setOnItemClcik(new BaseRecyclerAdp.ItemClick<SearchResultItem>() {
            @Override
            public void onItemClick(int position, SearchResultItem bean) {
                Toast.makeText(MainAct.this, bean.toString(), Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DbModel model = DbFactory.getInstance().openSession(SearchResultItem.class);
                LogUtil.i(TAG, "MainAct:onCreate: [ddddddd]= " + model.queryCount());
                model.deleteAll();

//                CustomApplication.getInstance().mVolleyQueue.add(request);

            }
        });

//        sql()IncrementalChange;


//        if (bean != null) {
//            textView.setText(bean.toString());
//        }else{
//            Toast.makeText(this,"",Toast.LENGTH_LONG).show();
//        }
        try {
//            TypeReference<JsonBean> beanTypeReference=new TypeReference<>();
//            beanTypeReference.getType();
//            JsonBeanMap bean=    JSON.parseObject(json,new TypeReference<JsonBeanMap>(){}.getType());
//            textView.setText( bean.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addnum() {
        for (int i = 0; i < 100; i++) {
            SearchResultItem bean = new SearchResultItem();
            bean.setName("name= " + i + " " + System.currentTimeMillis());
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < 6; j++) {
                int random = (int) Math.round(Math.random() * 25 + 97);
                char temp = (char) random;
                builder.append(temp);
            }
            Random random = new Random();
            bean.setPinyin(builder.toString());
            int data = random.nextInt(100000) + 100000;
            bean.setStockID(data + "");
            bean.setZimu(builder.toString() + data);
            bean.setSubtype(subtype[i % 3]);
            beanList.add(bean);
        }
    }

    private List<SearchResultItemBean> addnumBean() {
        List<SearchResultItemBean> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            SearchResultItemBean bean = new SearchResultItemBean();
            bean.setName("name= " + i + " " + System.currentTimeMillis());
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < 6; j++) {
                int random = (int) Math.round(Math.random() * 25 + 97);
                char temp = (char) random;
                builder.append(temp);
            }
            Random random = new Random();
            bean.setPinyin(builder.toString());
            int data = random.nextInt(100000) + 100000;
            bean.setStockID(data + "");
            bean.setZimu(builder.toString() + data);
            bean.setSubtype(subtype[i % 3]);
            list.add(bean);
        }
        return list;
    }

    public void onMitakeEvent(String string) {
        Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
    }

    public void onMitakeData(BaseBean string) {
        Toast.makeText(this, "string", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MitakeBus.getDefaut().unRegister(this);
    }

    private void sql() {
        parms = new HashMap<>();
        dao = new LoginUpBeanDao();
        LogUtil.i(true, TAG, "MainAct: onCreate: [dddddd]="
                + dao.queryOne(100));

        dao.delete(100);


//        LoginBean bean = new LoginBean("15555986853", "123456");
//        String str = JSON.toJSONString(bean);
//        parms.put("data", str);
        request = new StringRequest(Request.Method.GET,
                "http://10.96.227.24:8080/MyWeb3/login.spring?userName=15555986853&password=123456",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        LoginBean bean = JSON.parseObject(response, LoginBean.class);
                        dao.insert(bean);
                        LogUtil.i(true, TAG, "MainAct: onResponse: [response]="
                                + response);
                        LogUtil.i(true, TAG, "MainAct: onResponse: [ffffff]="
                                + dao.queryOne(100));

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtil.i(true, TAG, "MainAct: onErrorResponse: [error]="
                        + error);
            }
        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return parms;
            }

        };
        findViewById(R.id.main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.i(true, TAG, "MainAct: onClick: [ddddddd]="
                        + dao.queryList());


//                CustomApplication.getInstance().mVolleyQueue.add(request);

            }
        });
    }
}
